/*
 * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.example.marker.service.impl;

import cn.hutool.core.date.DateUtil;
import org.example.marker.service.UidGeneratorService;
import org.example.marker.service.WorkerIdAssigner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author Wills
 * @date 2020/05/26
 */
@Service("defaultUidGeneratorService")
public class DefaultUidGeneratorServiceImpl implements UidGeneratorService, InitializingBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultUidGeneratorServiceImpl.class);

    @Autowired
    protected BitsAllocator bitsAllocator;
    protected long workerId;

    protected long sequence = 0L;
    protected long lastSecond = -1L;

    @Autowired
    protected WorkerIdAssigner workerIdAssigner;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.workerId = this.workerIdAssigner.assignWorkerId();
        if (this.workerId > this.bitsAllocator.getMaxWorkerId()) {
            throw new RuntimeException( "Worker id " + this.workerId + " exceeds the max " + this.bitsAllocator.getMaxWorkerId());
        }
        LOGGER.info("Initialized bits(1, {}, {}, {}, {}) for workerID:{}",
                this.bitsAllocator.getAppBits(),
                this.bitsAllocator.getTimestampBits(),
                this.bitsAllocator.getWorkerIdBits(),
                this.bitsAllocator.getSequenceBits(),
                this.workerId);
    }

    @Override
    public long getUID(long appId) {
        if (appId > this.bitsAllocator.getMaxAppId()) {
            throw new RuntimeException("appId cannot max than " + this.bitsAllocator.getMaxAppId());
        }
        return this.nextId(appId);
    }

    @Override
    public String parseUID(long uid) {
        long totalBits = BitsAllocator.TOTAL_BITS;
        long signBits = this.bitsAllocator.getSignBits();
        long appBits = this.bitsAllocator.getAppBits();
        long timestampBits = this.bitsAllocator.getTimestampBits();
        long workerIdBits = this.bitsAllocator.getWorkerIdBits();
        long sequenceBits = this.bitsAllocator.getSequenceBits();
        long blankBits = this.bitsAllocator.getBlankBits();

        long sequence = (uid << (totalBits - sequenceBits)) >>> (totalBits - sequenceBits);
        long workerId = (uid << (timestampBits + appBits + signBits + blankBits)) >>> (totalBits - workerIdBits);
        long appId = uid >>> (timestampBits + workerIdBits + sequenceBits);
        long deltaSeconds = (uid << (appBits + signBits + blankBits)) >>> (totalBits - timestampBits);

        Date thatTime = new Date(TimeUnit.SECONDS.toMillis(this.bitsAllocator.getEpochSeconds() + deltaSeconds));
        String thatTimeStr = DateUtil.format(thatTime,"yyyy-MM-dd HH:mm:ss");

        return String.format("{\"UID\":\"%d\",\"appId\":\"%d\",\"timestamp\":\"%s\",\"workerId\":\"%d\",\"sequence\":\"%d\"}",
                uid, appId, thatTimeStr, workerId, sequence);
    }

    protected synchronized long nextId(long appId) {
        long currentSecond = this.getCurrentSecond();

        // Clock moved backwards, refuse to generate uid
        if (currentSecond < this.lastSecond) {
            long refusedSeconds = this.lastSecond - currentSecond;
            throw new RuntimeException(String.format("Clock moved backwards. Refusing for %d seconds", refusedSeconds));
        }

        if (currentSecond == this.lastSecond) {
            // At the same second, increase sequence
            this.sequence = (this.sequence + 1) & this.bitsAllocator.getMaxSequence();
            // Exceed the max sequence, we wait the next second to generate uid
            if (this.sequence == 0) {
                currentSecond = this.getNextSecond(this.lastSecond);
            }
        } else {
            // At the different second, sequence restart from zero
            this.sequence = 0L;
        }
        this.lastSecond = currentSecond;
        return this.bitsAllocator.allocate(appId, currentSecond - this.bitsAllocator.getEpochSeconds(), this.workerId, this.sequence);
    }

    private long getNextSecond(long lastTimestamp) {
        long timestamp = this.getCurrentSecond();
        while (timestamp <= lastTimestamp) {
            timestamp = this.getCurrentSecond();
        }
        return timestamp;
    }

    private long getCurrentSecond() {
        long currentSecond = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        if (currentSecond - this.bitsAllocator.getEpochSeconds() > this.bitsAllocator.getMaxDeltaSeconds()) {
            throw new RuntimeException("Timestamp bits is exhausted. Refusing UID generate. Now: " + currentSecond);
        }
        return currentSecond;
    }
}
